package com.hzmall.service.impl;

import com.hzmall.common.ResponseCode;
import com.hzmall.common.ServerResponse;
import com.hzmall.dao.CartMapper;
import com.hzmall.dao.ProductMapper;
import com.hzmall.pojo.Cart;
import com.hzmall.pojo.Product;
import com.hzmall.service.ICartService;
import com.hzmall.util.BigDecimalUtil;
import com.hzmall.util.PropertiesUtil;
import com.hzmall.vo.CartProductVo;
import com.hzmall.vo.CartVo;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("cartService")
public class CartService implements ICartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    //购物车列表
    public ServerResponse list(Integer userId){
        List<Cart> cartList = this.cartMapper.selectCartByUserId(userId);
        List<CartProductVo> cartProductVoList = new ArrayList<CartProductVo>();
        for (Cart cart : cartList){
            Product product = this.productMapper.selectByPrimaryKey(cart.getProductId());
            CartProductVo cartProductVo = convertProduct2CartProductVo(product);
            cartProductVo.setQuantity(cart.getQuantity());
            cartProductVo.setUserId(userId);
            cartProductVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
            cartProductVo.setId(cart.getId());
            cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(cart.getQuantity().doubleValue(),product.getPrice().doubleValue()));
            cartProductVo.setProductChecked(cart.getChecked());
            if (cart.getQuantity() > product.getStock()){
                Cart updateCart = new Cart();
                updateCart.setId(cart.getId());
                updateCart.setQuantity(product.getStock());
                this.cartMapper.updateByPrimaryKeySelective(updateCart);
                cartProductVo.setQuantity(product.getStock());
                cartProductVo.setLimitQuantity("LIMIT_NUM_SUCCESS");
            }else{
                cartProductVo.setLimitQuantity("LIMIT_NUM_FAIL");
            }
            cartProductVoList.add(cartProductVo);
        }
        CartVo cartVo = new CartVo();
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
        BigDecimal cartTotalPrice = new BigDecimal("0");
        for (CartProductVo cartProductVoItem : cartProductVoList) {
            if (cartProductVoItem.getProductChecked() == 1) {
                cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVoItem.getProductTotalPrice().doubleValue());
            }
        }
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setAllChecked(checkCartAllChecked(userId));
        return ServerResponse.createBySuccess(cartVo);
    }
    //Product转ProductVo
    public CartProductVo convertProduct2CartProductVo(Product product){
        CartProductVo cartProductVo = new CartProductVo();
        cartProductVo.setProductMainImage(product.getMainImage());
        cartProductVo.setProductName(product.getName());
        cartProductVo.setProductId(product.getId());
        cartProductVo.setProductPrice(product.getPrice());
        cartProductVo.setProductStatus(product.getStatus());
        cartProductVo.setProductStock(product.getStock());
        cartProductVo.setProductSubtitle(product.getSubtitle());
        return cartProductVo;
    }
    //判断当前用户购物车是否都是选中状态
    private Boolean checkCartAllChecked(Integer userId){
        Integer rows = this.cartMapper.selectUnCheckedCartByUserId(userId);
        return rows <= 0;
    }

    @Override
    public ServerResponse add(Integer userId, Integer productId, Integer count) {
        Product product = this.productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServerResponse.createByErrorMessage("该商品不存在");
        }
        Cart cart = this.cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if (cart != null){
            Cart updateCart = new Cart();
            updateCart.setId(cart.getId());
            updateCart.setQuantity(cart.getQuantity()+count);
            this.cartMapper.updateByPrimaryKeySelective(updateCart);
            ServerResponse serverResponse = list(userId);
            CartVo cartVo = (CartVo) serverResponse.getData();
            return ServerResponse.createBySuccess(cartVo,"更新数量成功");
        }
        Integer rows = this.cartMapper.insertProductIntoCart(userId, productId, count);
        if (rows > 0){
            ServerResponse serverResponse = list(userId);
            CartVo cartVo = (CartVo) serverResponse.getData();
            return ServerResponse.createBySuccess(cartVo,"增加商品成功");
        }
        return ServerResponse.createByErrorMessage("增加购物车失败");
    }

    //更新购物车某个产品数量
    public ServerResponse update(Integer userId, Integer productId, Integer count){
        Cart cart = this.cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if (cart == null){
            return ServerResponse.createByErrorMessage("该商品不在购物车中");
        }
        Cart updateCart = new Cart();
        updateCart.setId(cart.getId());
        updateCart.setQuantity(cart.getQuantity()+count);
        this.cartMapper.updateByPrimaryKeySelective(updateCart);
        ServerResponse serverResponse = list(userId);
        CartVo cartVo = (CartVo) serverResponse.getData();
        return ServerResponse.createBySuccess(cartVo,"更新数量成功");
    }

    //移除购物车某个产品
    public ServerResponse deleteProduct(Integer userId,Integer[] productIds){
        Integer rows = 0;
        if (ArrayUtils.isEmpty(productIds)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUEMENT.getCode(),ResponseCode.ILLEGAL_ARGUEMENT.getDesc());
        }
        for (Integer productId : productIds){
            Cart cart = this.cartMapper.selectCartByUserIdAndProductId(userId,productId);
            if (cart == null){
                continue;
            }
            rows = this.cartMapper.deleteCartByProductId(productIds,userId);
        }
        if (rows > 0){
            ServerResponse serverResponse = list(userId);
            CartVo cartVo = (CartVo) serverResponse.getData();
            return ServerResponse.createBySuccess(cartVo);
        }
        return ServerResponse.createByErrorMessage("移除失败");
    }

    //购物车选中商品
    public ServerResponse select(Integer userId, Integer productId){
        if (productId == null){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        Cart cart = this.cartMapper.selectCartByUserIdAndProductId(userId,productId);
        if (cart != null && cart.getChecked() == 0) {
            Cart updateCart = new Cart();
            updateCart.setId(cart.getId());
            updateCart.setChecked(1);
            Integer rows = this.cartMapper.updateByPrimaryKeySelective(updateCart);
        }
        ServerResponse serverResponse = list(userId);
        CartVo cartVo = (CartVo) serverResponse.getData();
        return ServerResponse.createBySuccess(cartVo);
    }

    //购物车取消选中商品
    public ServerResponse unSelect(Integer userId,Integer productId){
        if (productId == null){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        Cart cart = this.cartMapper.selectCartByUserIdAndProductId(userId,productId);
        if (cart != null && cart.getChecked() == 1){
            Cart updateCart = new Cart();
            updateCart.setId(cart.getId());
            updateCart.setChecked(0);
            this.cartMapper.updateByPrimaryKeySelective(updateCart);
        }
        ServerResponse serverResponse = list(userId);
        CartVo cartVo = (CartVo) serverResponse.getData();
        return ServerResponse.createBySuccess(cartVo);
    }

    //获取购物车中的商品总数
    public ServerResponse getCartProductCount(Integer userId){
        Integer count = 0;
        List<Cart> cartList = this.cartMapper.selectCartByUserId(userId);
        if (cartList != null){
            for (Cart cart : cartList){
                count = count + cart.getQuantity();
            }
        }
        return ServerResponse.createBySuccess(count);
    }

    //全选购物车
    public ServerResponse selectAll(Integer userId){
        this.cartMapper.updateAllCartChecked(userId);
        ServerResponse response = list(userId);
        CartVo cartVo = (CartVo) response.getData();
        return ServerResponse.createBySuccess(cartVo);
    }

    //全不选购物车
    public ServerResponse unSelectAll(Integer userId){
        this.cartMapper.updateAllCartUnChecked(userId);
        ServerResponse response = list(userId);
        CartVo cartVo = (CartVo) response.getData();
        return ServerResponse.createBySuccess(cartVo);
    }
}
